<template>
  <view :class="[(speciShow || showCoupon || serviceFlag || regionShow || showPromtion) ? 'hide' : '', 'shopDetail']">
    <navBar
      :custom-els="customEls"
      :bg-color="`white`"
      :current="current"
      :back-executor="(isFromSharedCard || isFromWeiXinScan || isFromLoginPage) ? backHomeExecutor : null"
      @tabClick="tabClick"
    />
    <view class="anchor" />
    <u-swiper
      :list="imageInfos"
      key-name="imgUrl"
      indicator-style="right: 32rpx;bottom: 32rpx"
      height="750rpx"
      radius="0"
      class="swiperName"
      @change="change"
    >
      <view slot="indicator" class="indicator-num">
        <view class="indicator-num__text">
          <view class="Active">{{ currentNum + 1 }}</view>
          <view class="allLength">{{ imageInfos.length }}</view>
        </view>
      </view>
    </u-swiper>
    <!--商品信息部分-->
    <view class="shopInfo">
      <view class="shopSpeci">
        <view class="timeOut">
          <view>  <!--有活动展示活动价和售价-->
            <view v-if="detailInfo.disPrice" class="Price">￥<text class="Number">{{ Number(detailInfo.disPrice).toFixed(2) || '' }}</text>/{{ detailInfo.unitName || '' }}</view>
            <view v-if="detailInfo.priceAccuracyTag == 0" class="redprice">该商品价格仅供参考，如需购买，请先询价</view>
            <view v-if="!!detailInfo.delPrice" class="oldPrice">￥{{ detailInfo.delPrice || '' }}/{{ detailInfo.unitName || '' }}</view>
          </view>
          <view v-if="detailInfo.activityFlag" class="time">
            <u-count-down :time="stampTime" format="DD:HH:mm" auto-start millisecond @change="onChange">
              剩余：{{ timeData.days }}天{{ timeData.hours>10?timeData.hours:'0'+timeData.hours }}时{{ timeData.minutes }}分
            </u-count-down>
          </view>
        </view>
        <view
          v-if="detailInfo.activityFlag || isHazardousProduct"
          class="activity"
        >
          <!-- <view class="tabs">
            <template v-if="detailInfo.activityFlag">
              <view v-if="detailInfo.skuActivityInfo.activityType == 10" class="default">特价</view>
              <view v-if="detailInfo.skuActivityInfo.activityType == 20" class="default">促销</view>
              <view v-for="(item, index) in couponsList" v-if="index < 2" :key="index" class="coupons">满{{ item.couponUseCondition }}减{{ item.couponValue }}</view>
            </template>
            <view v-if="isHazardousProduct" class="coupons">危化品</view>
          </view> -->
          <!-- 特价 促销 危化品精选畅销标签 开始 -->
          <view class="tabs">
            <template v-if="detailInfo.activityFlag">
              <view v-if="detailInfo.skuActivityInfo.activityType == 10" class="default">特价</view>
              <view v-if="detailInfo.skuActivityInfo.activityType == 20" class="default">促销</view>
            </template>
            <view v-if="isHazardousProduct" class="coupons">危化品</view>
          </view>
          <!-- 特价 促销 危化品精选畅销标签 结束 -->

          <!-- <view class="moreCop">
            <view v-if="couponsList.length > 2">...</view>
            <u-icon name="arrow-right" class="defaultStyle" />
          </view> -->
        </view>
        <view class="shopName">{{ detailInfo.spuName || '' }}  {{ detailInfo.specificationProperties || '' }}</view>
        <view v-show="!!detailInfo.subtitle" class="describe">{{ detailInfo.subtitle }}</view>
        <view class="shopCode">
          <view>商品编码：<text>{{ detailInfo.skuCode }}</text></view>
          <view class="copy" @click="copy">复制</view>
        </view>
        <!-- 云采，各客户端隐藏未税价、税率 -->
        <!-- <view class="tax">
          未税单价：<text class="taxPrice">¥ {{detailInfo.noTaxPrice || ''}}</text>
          <view class="taxRate">税率：<text>{{(detailInfo.revenueRate || 0 )* 100}}%</text></view>
        </view> -->
      </view>
    </view>
    <!--商品信息部分 end#########################################-->

    <!--商品规格部分-->
    <view class="addressSpeci">
      <view class="addressSpeci_small">
        <!--规格部分-->
        <view class="speci" @click="showSpeciFn">
          <view class="label">
            <view class="labelName">规格：</view>
            <view style="color: #000000;" class="eslineHide">已选：{{ detailInfo.specificationProperties || '' }}</view>
          </view>
          <view style="display:flex;">{{ newSkuInfos.length }}个规格<u-icon name="arrow-right" /></view>
        </view>
        <!--规格部分 end##################################-->
        <!--领券部分 优惠券和促销没关系 未登不显示登录就显示-->
        <view  class="speci activity" v-if="couponsList.length >0" @click="handleClickActivity">
          <view class="label">
            <view class="labelName">领券：</view>
            <view class="tabs">
              <template>
                <view v-for="(item, index) in couponsList" v-if="index < 2" :key="index" class="coupons">满{{ item.couponUseCondition }}减{{ item.couponValue }}</view>
              </template>
            </view>
          </view>
          <view style="display:flex;"><u-icon name="arrow-right" /></view>
        </view>
        <!--领券部分end##################################---->
        <!--促销部分-->
        <view v-if="detailInfo.activityFlag " class="speci activity" @click="handleClickActivityPromtion">
          <view class="label">
            <view class="labelName">促销：</view>
            <view class="tabs">
              <view v-if="detailInfo.skuActivityInfo.activityType == 10" class="activiy">
                <!-- 特价标签 -->
                <view class="t-icon t-icon-tejia_tongyong_1" />
                <view class="con-right">
                  <view class="tips">{{ detailInfo.couponTips }}</view>
                </view>
              </view>
              <view v-if="detailInfo.skuActivityInfo.activityType == 20" class="activiy">
                <!-- 满减标签 -->
                <view class="t-icon t-icon-manjian_tongyong_1" />
                <view class="con-right">
                  <view class="tips">{{ detailInfo.couponTips }}</view>
                </view>
              </view>
            </view>
          </view>
          <view style="display:flex;"><u-icon name="arrow-right" /></view>
        </view>
        <!--促销部分 end##################################---->

        <!--配送部分-->
        <view class="speci" style="margin-top: 24rpx;" @click="showRegionFn">
          <view class="label">
            <view class="labelName">配送：</view>
            <view style="color: #000000;display: flex"><u-icon name="map" />{{ nowAddress.name }}</view>
          </view>
          <u-icon name="arrow-right" />
        </view>
        <view v-if="!!detailInfo.arrivalCycle" class="deliverShop" :style="{'paddingLeft': detailInfo.skuStockInfo.actualStock < shopNum ? '84rpx' : ''}">
          <text v-if="detailInfo.skuStockInfo.actualStock >= shopNum" class="t-icon t-icon-xianhuo_tongyong_1" />
          预计出货日：{{ detailInfo.arrivalCycle }}天
        </view>
        <!--配送部分 end##################################-->
        <!--服务部分-->
        <view class="speci" style="margin-top: 24rpx;" @click="showServiceFn">
          <view class="label">
            <view class="labelName">服务：</view>
            <view class="tabsServe">
              <view>
                <text class="font_family icon-shield_tongyong_1" />
                正品保障
              </view>
              <view>
                <text class="font_family icon-truck_tongyong_2" />
                30天退换
              </view>
              <view>
                <text class="font_family icon-wrench_tongyong_1" />
                维修服务
              </view>
            </view>
          </view>
          <u-icon name="arrow-right" />
        </view>
        <!--服务部分 end##################################-->
      </view>
    </view>
    <!--商品规格部分 end##################################-->

    <view class="detailImage">
      <view class="line">
        <view>商品详情</view>
      </view>
      <mp-html :content="detailInfo.appDetail" />
    </view>

    <view class="recomShop">
      <view class="title">相关产品</view>
      <view class="recomShopList">
        <view v-for="(item, index) in recomShopList" :key="index" class="small">
          <recomShop :obj="item" />
        </view>
      </view>
    </view>
    <couponPopup
      v-if="couponsList.length > 0||1"
      :show-coupon.sync="showCoupon"
      :coupon-info="detailInfo"
      :coupons-list="couponsList"
      @getCoupons="getCoupons"
    />
    <promotionPopup
      v-if="couponsList.length > 0||1"
      :show-promtion.sync="showPromtion"
      :coupon-info="detailInfo"
      @getCoupons="getCoupons"
    />
    <serviceInfoPopup :service-flag="serviceFlag" @closeServiceFn="closeServiceFn" />
    <shopFooter
      :product-type="productType"
      :sale-flag="saleFlag"
      :coll-info="collInfo"
      :cart-count="cartCount"
      :branch-name="branchName"
      :detail-info="detailInfo"
      :branch-id="branchId"
      use-type="index"
      :speci-show.sync="speciShow"
      @addShopCar="addShopCar"
      @CollectionShop="CollectionShop"
      @buy="buy"
    />
    <!--避免组件多层嵌套。不拆出去了-->
    <view class="regionPopup">
      <u-popup :show="regionShow" :round="10" mode="bottom">
        <view class="title">
          配送 <image src="./static/image/close.png" @click="closeRegionFn" />
        </view>
        <view v-if="regionShow" :style="'height:' + height + 'px;'">
          <region :save-flag="true" @getParams="getParams(arguments)" />
        </view>
      </u-popup>
    </view>
    <speciPopup
      :product-type="productType"
      :speci-show="speciShow"
      :shop-num.sync="shopNum"
      :default-shop-num.sync="defaultShopNum"
      :order-limit-type.sync="orderLimitType"
      :detail-info="detailInfo"
      :new-sku-infos="newSkuInfos"
      :sale-flag="saleFlag"
      :share-member-id="shareMemberId"
      @closeSpeciFn="closeSpeciFn"
      @changeSpeci="changeSpeci"
      @addShopCar="addShopCar"
      @buy="buy"
    />
    <text v-if="showToppting" class="font_family topping icon-Top_tongyong_1" @click="gotop()" />
  </view>
</template>

<script>

import navBar from '@/components/navBar'
import region from '@/components/region'
import recomShop from './recomShop/shop'
import shopFooter from './recomShop/shopFooter'
import couponPopup from './recomShop/couponPopup'
import promotionPopup from './recomShop/promotionPopup'
import serviceInfoPopup from './recomShop/serviceInfoPopup'
import speciPopup from './recomShop/speciPopup'
import {
  getNavHeight,
  getLocationFn,
} from '@/common/common'
import {
  getShopDetail,
  getReleShop,
  getCoupons,
  CollectionShop,
  cancelColl,
  getCollId,
  getCarNum,
  getProductTypeBySkuOrSpu,
  tempProductDetailByApp,
  twinsProductDetailByApp,
  providerProductDetailByApp,
  recordMemberShareLog
} from '@/api/shopDetail'
import { addShopCar } from '@/api/shopCar'
import qs from '@/lib/qs'

export default {
  components: {
    navBar,
    recomShop,
    shopFooter,
    serviceInfoPopup,
    region,
    couponPopup,
    speciPopup,
    promotionPopup
  },
  data() {
    return {
      customEls: ['shopDetail'],
      currentNum: 0,
      timeData: {},
      showCoupon: false, // 优惠信息flag
      showPromtion: false, //促销 flag
      serviceFlag: false, //服务信息flag
      regionShow: false, // 选择区域
      speciShow: false, // 规格信息flag
      height: 0,
      detailInfo: {},
      newSkuInfos: [],
      nowAddress: {},
      recomShopList: [],
      couponsList: [],
      stampTime: '',
      nowStampTime: '',
      imageInfos: [],
      recomTop: '',
      detailTop: '',
      bannerTop: 100,
      current: 0,
      spuCode: '',
      skuCode: '',
      saleFlag: false,
      shopNum: 1,
      defaultShopNum: 1,
      orderLimitType: 1,
      platformType: '',
      collInfo: {},
      cartCount: 0,
      branchId: '',
      branchName: '',
      showToppting: false,
      isFromSharedCard: false, // 是从分享小程序卡片进入
      isFromWeiXinScan: false, // 是从微信扫码进入
      isFromLoginPage: false, // 是从登录页面进入
      isHazardousProduct: false, // 是危化品商品
      productType: '', // 商品类型
      shareMemberId: '', //初始化进入如果当前链接是分享进入的 需要根据分享人shareMemberId 来绑定当前商品用于分享数据统计
    }
  },
  onLoad(option) {
    console.log('商品详情接参测试分享卡片', option.shareMemberId, this.vuex_memberInfo.memberId)
    console.log(option)
    this.shareMemberId = option.shareMemberId
    this.initPageFn(option)
    console.log('分享人idshareMemberId', this.shareMemberId)
  },

  onShareAppMessage(res) {
    if (res.from === 'button') { // 来自页面内分享按钮
      console.log(res.target)
    }
    const { companyName = '', pushmanCompanyId = '', memberId } = this.vuex_memberInfo
    const [title, imageUrl] = this.getShareCardInfo()
    return {
      title,
      imageUrl,
      path: `/shopDetail/index?spuCode=${this.spuCode}&skuCode=${this.skuCode}&fromCard=${true}&branchId=${pushmanCompanyId}&branchName=${companyName}&shareMemberId=${memberId}`
    }
  },
  methods: {

    //初始化进入如果当前链接是分享进入的 需要根据分享人shareMemberId 来绑定当前商品用于分享数据统计
    shareFn() {
      console.log('详情spuskus值', this.skuCode, this.spuCode)
      const { memberId } = this.vuex_memberInfo
      if (this.shareMemberId == 'undefined') {
        this.shareMemberId = ''
      }
      console.log('分享人获取值idshareMemberId', this.shareMemberId)
      const params = {
        shareMemberId: this.shareMemberId, //分享人id
        byMemberId: memberId || '', //被分享人id
        skuCode: this.skuCode || '', //商品sku编码
        spuCode: this.spuCode || '', //商品spu编码
      }
      console.log('分享接口数据', params)
      recordMemberShareLog(params).then((res) => {
        if (res.code == 0) {
          console.log('分享接口数据返回', res)
          // this.$u.toast(res.msg)
        } else {
          // this.$u.toast(res.msg)
        }
      })
    },
    /*异步初始化页面
    * 没有地址定位时候先获取定位地址*/
    async initPageFn(option) {
      if (!this.vuex_nowAddress) {
        getLocationFn(this.initDataFn, option)
        return
      }
      this.initDataFn(option)
    },
    // 获取商品类型
    async getProductType(spuCode) {
      const isIncludesSPU = /[SPU]/.test(spuCode)
      const skuCode = isIncludesSPU ? spuCode.replace('SPU', '') : '' // 临采商品编码含SPU，此时入参传skuCode（去除SPU字符）
      const res = await getProductTypeBySkuOrSpu({ skuCode, spuCode })
      if (res.errorCode == 0) {
        this.productType = res.data?.productType
      }
    },
    // 获取查询详情接口请求
    getProductDetailsService() {
      const serviceMaps = {
        1: getShopDetail, // 正常商品
        2: tempProductDetailByApp, // 临采商品-线索
        4: twinsProductDetailByApp, //一物多码商品  
        3: providerProductDetailByApp, // 供货商商品
        6: tempProductDetailByApp // 临采商品-潜在
      }
      const requestFn = serviceMaps[this.productType] ?? getShopDetail
      return requestFn
    },
    // 点击活动区域
    handleClickActivity() {
      console.log('优惠券弹框', this.detailInfo)
        this.showCoupon = true
    },
    //点击促销区域
    handleClickActivityPromtion() {
      if (this.detailInfo.activityFlag) {
        console.log('促销弹框', this.detailInfo)
        this.showPromtion = true
      }
    },
    /*初始化数据*/
    async initDataFn(option) {
      this.height = uni.getSystemInfoSync().windowHeight - getNavHeight() - uni.upx2px(150)
      this.nowAddress = this.vuex_nowAddress
      if (option.q) { // 微信扫码
        this.executeWeiXinScanResult(option.q)
      } else if (this.vuex_alipay_qrcode) { // 支付宝扫码
        this.executeWeiXinScanResult(this.vuex_alipay_qrcode)
      } else {
        this.spuCode = option.spuCode
        this.skuCode = option.skuCode
      }
      await this.getProductType(this.spuCode)
      const IS_TEMP_PRODUCT = 2 // 临采商品
      const IS_TEMP_PRODUCT6 = 6 // 临采商品
      if (this.productType == IS_TEMP_PRODUCT || this.productType == IS_TEMP_PRODUCT6) {
        this.spuCode = this.spuCode.replace('SPU', '')
      }
      this.getShopDetail(this.spuCode, this.skuCode)
      /*uni.showShareMenu()*/
      this.setPlateformTypeFn()
      this.vuex_loginStatus ? this.getCarNum() : (this.cartCount = 0)
      const { branchId, branchName, fromCard, isFromLoagin } = option
      this.branchId = branchId
      this.branchName = branchName
      if (!this.vuex_sharePushmanCompanyInfo || Object.keys(this.vuex_sharePushmanCompanyInfo).length == 0) {
        this.$u.vuex('vuex_sharePushmanCompanyInfo', { branchId, branchName })
      }
      this.isFromSharedCard = fromCard // 接受是否来自分享卡片的状态
      this.isFromLoginPage = isFromLoagin ?? false // 是否来自登录页面
      // if (!!!this.vuex_loginStatus || !this.vuex_loginStatus) {
      //   this.cartCount = 0
      // } else {
      //   this.getCarNum()
      // }
      this.shareFn()
    },
    // 获取分享卡片信息
    getShareCardInfo() {
      const { disPrice, spuName, specificationProperties } = this.detailInfo
      const title = `【${disPrice}元】 ${spuName} ${specificationProperties}` // 标题 = SKU售价 + SKU名称
      const imageUrl = this.imageInfos[0]?.imgUrl // 图片 = 商品主图（第一张）
      return [title, imageUrl]
    },
    // 返回主页
    backHomeExecutor() {
      uni.redirectTo({ url: '/pages/index/index' })
    },
    gotop() {
      uni.pageScrollTo({
        duration: 500,
        scrollTop: 0
      })
    },
    buy() {
      if (this.saleFlag) return
      const { skuCode, disPrice, spuCode, priceAccuracyTag } = this.detailInfo
      const { onActivityId } = this.detailInfo?.skuActivityInfo ?? {}
      if (priceAccuracyTag == 0) {
        return this.$u.toast('该商品价格仅供参考，如需购买，请先询价');
      }
      const skuList = [
        {
          skuCode,
          buyyerCount: this.shopNum,
          salePrice: disPrice,
          joinPromotionTag: '10',
          activityId: onActivityId
        }
      ]
      const opsObj = {
        itemId: '',
        opsRequestMisc: '',
        requestId: '',
        spuCode
      }
      uni.navigateTo({
        url: `/ycPayments/confirmOrders/index?skuList=${encodeURIComponent(JSON.stringify(skuList))}&opsObj=${encodeURIComponent(JSON.stringify(opsObj))}`
      })
    },
    async getCollId(title) { // 最后执行此方法
      const { memberId } = this.vuex_accountInfo
      const { skuCode } = this.detailInfo
      const params = {
        member_id: memberId,
        skuCode,
        appletType: 'applet'
      }
      const res = await getCollId(params)
      if (res.errorCode == 1) {
        this.collInfo = res
        if (title) this.$u.toast(title)
        if (this.saleFlag) {
          this.$u.toast('该商品此区域暂不支持销售，非常抱歉！');
        }
      }
    },
    async getCarNum(title) { //查询购物车数量
      const { memberId, customerId } = this.vuex_memberInfo
      const params = {
        memberId,
        customerId
      }
      const res = await getCarNum(params)
      if (res.errorCode == 1) {
        this.cartCount = res.result1.cartCount
        if (title) this.$u.toast(title)
      }
    },
    setPlateformTypeFn() { // 平台值转化
      if (Object.keys(this.vuex_memberInfo).length == 0) return
      switch (this.vuex_memberInfo.accountType) { // 账户类型：10:签约用户；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
        case 10:
          this.platformType = 1
          break
        case 20:
          this.platformType = 2
          break
        case 30:
          this.platformType = 2
          break
        case 39:
          this.platformType = 3
          break
        case 40:
          this.platformType = 3
          break
        default:
          this.platformType = 2
          break
      }
    },
    async CollectionShop(id) { // 收藏
      const { memberId } = this.vuex_accountInfo
      const { warehouseCode, cityCode } = this.vuex_cityInfo
      const { skuCode } = this.detailInfo
      const params = {
        skuCode: skuCode,
        cityId: cityCode,
        warehouseId: warehouseCode,
        member_id: memberId,
        source: '40',
        platformType: this.platformType,
        collectId: id,
        appletType: 'applet'
      }
      if (id) {
        const cancel = await cancelColl(params)
        if (cancel.errorCode == 1) {
          this.getCollId('取消收藏成功')
        }
      } else {
        const res = await CollectionShop(params)
        if (res.errorCode == 1) {
          this.getCollId('收藏成功')
        }
      }
    },
    async addShopCar() { // 加入购物车
      if (this.saleFlag) return
      const { memberId } = this.vuex_accountInfo
      const { warehouseCode, cityCode } = this.vuex_cityInfo
      const { skuId, skuCode, priceAccuracyTag } = this.detailInfo
      var skuIdNumlist = [{ skuId, skuCode, skuNum: this.shopNum }]
      const params = {
        member_id: memberId,
        cityId: cityCode,
        warehouseId: warehouseCode,
        source: '40', // android=>10;ios=>20;wap=>30;pc=>40
        skuIdNumlist
      }
      /**
      * priceAccuracyTag 正常商品价格准确性标记（0：价格不准确；40：售价绝对准确；50：售价相对准确）
      */
      console.log('商品详情加入购物车事件', this.detailInfo)
      if (priceAccuracyTag == 0) {
        return this.$u.toast('该商品价格仅供参考，如需购买，请先询价');
      }
      const res = await addShopCar(params)
      if (res.code == 0) {
        this.getCarNum(res.errorMessage);
        this.speciShow = false
      } else {
        this.$u.toast(res.message || res.errorMessage)
      }
    },
    tabClick(e) {
      var className = '.anchor'
      if (e.name == '商品') {
        className = '.anchor'
      } else if (e.name == '详情') {
        className = '.detailImage'
      } else {
        className = '.recomShop'
      }
      uni.createSelectorQuery().select('.shopDetail').boundingClientRect(data => { // 最外层的元素
        uni.createSelectorQuery().select(className).boundingClientRect((res) => { // 当前需要滚动到顶部元素的节点
          // #ifdef MP-ALIPAY || MP-WEIXIN
          uni.pageScrollTo({
            duration: 500,
            scrollTop: res.top - data.top - getNavHeight(), //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离减去自定义导航高度
          })
          // #endif
          // #ifdef H5
          uni.pageScrollTo({
            duration: 500,
            scrollTop: res.top - data.top - 44, //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离减去自定义导航高度
          })
          // #endif
        }).exec()
      }).exec();
    },
    getAllHeight() {
      uni.createSelectorQuery().select('.shopDetail').boundingClientRect(data => {
        uni.createSelectorQuery().select('.recomShop').boundingClientRect((res) => {
          // #ifdef MP-ALIPAY || MP-WEIXIN
          this.recomTop = res.top - data.top - getNavHeight()
          // #endif
          // #ifdef H5
          this.recomTop = res.top - data.top - 44
          // #endif
        }).exec()
        uni.createSelectorQuery().select('.detailImage').boundingClientRect(res => {
          // #ifdef MP-ALIPAY || MP-WEIXIN
          this.detailTop = res.top - data.top - getNavHeight()
          // #endif
          // #ifdef H5
          this.detailTop = res.top - data.top - 44
          // #endif
        }).exec();
      }).exec();
    },
    onPageScroll(e) {
      e.scrollTop > 600 ? this.showToppting = true : this.showToppting = false
      if (this.detailTop < e.scrollTop && e.scrollTop < this.recomTop) {
        this.current = 1
      } else if (e.scrollTop >= this.recomTop) {
        this.current = 2
      } else if (e.scrollTop <= this.bannerTop) {
        this.current = 0
      }
    },
    copy() {
      uni.setClipboardData({
        /* data: this.detailInfo.spuCode,*/
        data: this.detailInfo.skuCode,
        success: () => {
          uni.showToast({ title: '复制成功', icon: 'none' });
        }
      });
    },
    change(e) { // 轮播图播放事件。配合自定义显示对应下标
      this.currentNum = e.current
    },
    onChange(e) {
      this.timeData = e
    },
    // 服务信息弹框操作
    showServiceFn() {
      this.serviceFlag = true
    },
    closeServiceFn() {
      this.serviceFlag = false
    },
    // 配送区域
    showRegionFn() {
      this.regionShow = true
    },
    closeRegionFn() {
      this.regionShow = false
    },
    // 规格信息
    showSpeciFn() {
      this.speciShow = true
    },
    closeSpeciFn() {
      this.speciShow = false
    },
    changeSpeci(e) { // 规格选择操作
      this.detailInfo = e
      var activityEndTime = (!!e.skuActivityInfo && !!e.skuActivityInfo.activityEndTime) ? e.skuActivityInfo.activityEndTime : ''
      var stampActivityEndTime = new Date(activityEndTime.replace(/-/g, '/')).getTime(); // 切换后计算当前sku的活动结束时间
      this.stampTime = stampActivityEndTime - this.nowStampTime
      this.getCycle() // 重新计算预计出货日
      this.getCollId() // 获取选中的收藏状态
    },
    getReleva() {
      const { accountType, memberId, mainCustomerId, customerId } = this.vuex_memberInfo
      const { skuCode, categoryId, spuCode } = this.detailInfo
      const { cityCode, warehouseCode } = this.vuex_cityInfo
      var platformType = ''; var activityPerson = ''
      switch (accountType) { //  账户类型：10:签约用户；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
        case 10:
          platformType = 1
          activityPerson = 20
          break
        case 20:
          platformType = 2
          activityPerson = 10
          break
        case 30:
          platformType = 2
          activityPerson = 10
          break
        case 39:
          platformType = 3
          activityPerson = 30
          break
        case 40:
          platformType = 3
          activityPerson = 30
          break
        default:
          platformType = 2
          activityPerson = 10
          break
      }
      const params = {
        categoryLevel: 4,
        categoryId,
        skuCode,
        spuCode,
        memberId,
        cityCode,
        warehouse_code: warehouseCode,
        platformType,
        mainCustomerId,
        customerId,
        activityPerson
      }
      getReleShop(params).then((res) => {
        if (res.code == '0') {
          this.recomShopList = res.data
          if (memberId) {
            console.log('调取优惠券')
            this.getCoupons() // 获取优惠券
          }
        }
      })
    },
    getShopDetail(spuCode, skuCode) {
      console.log(spuCode, skuCode)
      // const skuCode = skuCode
      // const spuCode = spuCode
      const { warehouseCode, cityCode } = this.vuex_cityInfo
      const params = {
        spuCode,
        skuCode,
        cityCode: cityCode,
        warehouseId: warehouseCode,
        skuCodes:[skuCode] //此参数是在测试一物多码时发现的问题加的参数
        // spuCode: '100153',
        // cityCode: '110100',
        // warehouseId: 1
      }
      const getDetailsServiceFn = this.getProductDetailsService()
      getDetailsServiceFn(params).then((res) => {
        if (res.code == '0') {
          const { skuInfos = [] } = res
          const isTempGoods = this.productType == 2 || this.productType == 6 // 临采商品分为 线索 潜在
          this.saleFlag = !isTempGoods && skuInfos.some(item => item.isAvailableSales == 0) // 如果为0，则该区域不售卖该商品
          var filterSku = isTempGoods ? skuInfos : skuInfos.filter((item) => item.ycSalesStauts == 1) // 筛选售卖的规格sku
          if (filterSku.length == 0) {
            this.saleFlag = true
            return this.$u.toast('该商品此区域暂不支持销售，非常抱歉！');
          }
          this.newSkuInfos = filterSku.map((item) => { // 规格信息部分数据处理
            item.appDetail = item.appDetail ? item.appDetail.replace(/\<img/gi, '<img class="richImg"') : item.appDetail; // 替换详情数据
            item.revenueRate = (item.revenueRate == 0 || !item.revenueRate) ? 0.13 : item.revenueRate // 税率
            const { activityType, activityItemLimitNum, activityPlatform, isActivityBegin, activityPrice, activityFullStr } = item?.skuActivityInfo ?? {}
            const { skuPriceInfo: { costPrice, salePrice, retailPrice, scribingPrice }, unitName } = item
            const { accountType } = this.vuex_memberInfo
            console.log('平台',activityPlatform)
            if (accountType !== 20) { // 如果不是签约会员
            // activityPlatform ： 活动平台 10=不限；20=pc；30=移动端；40=小程序；50=M站   多选用逗号隔开的形式
              if (!!activityPlatform && (activityPlatform.indexOf('10') >= 0 || activityPlatform.indexOf('40')  >= 0 ) && !!isActivityBegin && isActivityBegin !== 1) {
                item.activityFlag = true //自定义当前有没有活动
                if (activityPrice < costPrice) { //当活动价小于成本价，直接使用成本价
                  item.disPrice = costPrice // disPrice 显示的价格
                  //item.delPrice = '' // delPrice 划线价，有活动显示售价 ===20231010 于后端张楚沟通修改暂时注销掉
                  item.conutPrice = costPrice
                } else { // 反之直接使用活动价
                  item.conutPrice = activityPrice;
                  item.disPrice = activityPrice
                  //item.delPrice = salePrice  ===20231010 于后端张楚沟通修改暂时注销掉
                }
                if (salePrice > activityPrice) { //划线价逻辑显示： 售价> 活动价 展示售价   ===20231010 于后端张楚沟通修改
                  item.delPrice = salePrice
                } else {
                  item.delPrice = ''
                }
              } else { // 没有活动价直接使用售价
                item.activityFlag = false
                item.conutPrice = salePrice;
                item.disPrice = salePrice // 没有活动，直接显示售价
                if (this.productType == 1) { //普通商品 划线价 retailPrice
                  item.delPrice = salePrice >= retailPrice ? '' : retailPrice // 当交易价等于或大于划线价时，不展示划线价，否则展示retailPrice
                }
                if (this.productType == 2 || this.productType == 6) { //线索潜在 划线价 scribingPrice
                  item.delPrice = salePrice >= scribingPrice ? '' : scribingPrice // 当交易价等于或大于划线价时，不展示划线价，否则展示scribingPrice
                }
              }
            } else { // 签约会员价格显示
              item.disPrice = salePrice // disPrice 显示的价格
              item.delPrice = retailPrice // delPrice 划线价，有活动显示售价
              if (salePrice < retailPrice) {
                item.delPrice = ''
              }
              item.conutPrice = salePrice
            }
            item.noTaxPrice = (item.conutPrice / (1 + Number(item.revenueRate))).toFixed(2); // 未税价计算
            if (activityType == 10) {
              if (activityItemLimitNum == 1) {
                item.couponTips = `前1${unitName}享受活动价,超出数量以原价计算!`
              } else if (activityItemLimitNum == 0) {
                item.couponTips = '活动期间，享受活动价，不限量'
              } else {
                item.couponTips = `前1-${activityItemLimitNum}/${unitName}享受活动价,超出数量以原价计算!`
              }
            } else if (activityType == 20) {
              if (activityFullStr) {
                item.couponTips = activityFullStr
              } else {
                item.couponTips = ''
              }
            }
            return item
          })
          //this.detailInfo = this.newSkuInfos[0]
          const detailInfoData = this.newSkuInfos[0]
          // #ifdef MP-WEIXIN
          const couponTipsMj = this.newSkuInfos[0].couponTips ? this.newSkuInfos[0].couponTips.replaceAll('#', this.newSkuInfos[0].unitName ? this.newSkuInfos[0].unitName : '') : ''
          this.detailInfo = { ...detailInfoData, couponTips: couponTipsMj }
          // #endif
          // #ifdef MP-ALIPAY
           const couponTipsMjA = this.newSkuInfos[0].couponTips?this.newSkuInfos[0].couponTips.split('#').join(this.newSkuInfos[0].unitName):''
          this.detailInfo = { ...detailInfoData, couponTips: couponTipsMjA }
          // #endif
        
          console.log(this.detailInfo, this.detailInfo.couponTips)

          this.isHazardousProduct = this.detailInfo.categoryProductType == 1 // categoryProductType - 1危化品 2 管制刀具 3非限制商品
          this.shopNum = Number(this.newSkuInfos[0].ycMiniOrder)
          this.defaultShopNum = Number(this.newSkuInfos[0].ycMiniOrder)
          this.orderLimitType = this.newSkuInfos[0].orderLimitType
          this.imageInfos = this.newSkuInfos[0].imageInfos || [] // 默认取第一个。后续改动sku不更新轮播
          const { activityEndTime } = this.newSkuInfos[0]?.skuActivityInfo ?? {}
          // const { skuActivityInfo: { activityEndTime }} = this.newSkuInfos[0] // 首次请求接口时默认赋值倒计时
          const { currentTime } = res
          this.nowStampTime = currentTime
          var stampActivityEndTime = activityEndTime ? new Date(activityEndTime.replace(/-/g, '/')).getTime() : stampActivityEndTime; // 活动结束时间
          var stampCurrentTime = currentTime ? new Date(currentTime.replace(/-/g, '/')).getTime() : stampCurrentTime; // 当前获取的时间
          this.stampTime = stampActivityEndTime - stampCurrentTime
          setInterval(() => { // 定时器刷新当前时间戳
            this.nowStampTime = stampCurrentTime - 1000
          }, 1000)
          this.getCycle() // 重新计算预计出货日
          this.getReleva() //转化推荐商品
          setTimeout(() => { this.getAllHeight() }, 500)
        }
      })
    },
    getCoupons() { // 获取优惠券
      const { accountType, memberId } = this.vuex_memberInfo
      const params = {
        skuCodes: [this.detailInfo.skuCode],
        member_id: memberId,
        account_type: accountType
      }
      getCoupons(params).then((res) => {
        if (res.code == '0') {
          this.couponsList = res.coupons.filter((item) => {
            return item.couponUseStatus == 0
          })
          console.log('优惠券数据', this.couponsList)
          this.getCollId() // 获取商品收藏信息
        }
      })
    },
    getCycle() { // 计算预计出货日
      const { skuStockInfo: { actualStock, arrivalCycle }} = this.detailInfo
      var Cycle = this.shopNum > actualStock ? Number(arrivalCycle) + 1 : 1 // 如果输入的数量大于库存数，预计出货日自动加一。反之不变
      if (Cycle > 10 && Cycle <= 30) {
        this.detailInfo.arrivalCycle = 10
      } else if (Cycle >= 30) {
        this.detailInfo.arrivalCycle = 30
      } else {
        this.detailInfo.arrivalCycle = Cycle
      }
    },
    getParams(e) {
      this.nowAddress = e[0]
      this.regionShow = false
      this.getShopDetail(this.spuCode, this.skuCode)
    },
    // 执行微信扫码结果
    executeWeiXinScanResult(qrCode) {
      const decodeUrl = decodeURIComponent(qrCode)
      // 微信扫描电子价签
      const executeTagScan = (url) => {
        const codeSuffix = url.split('/').pop() // 含有code编码的后缀html字符串
        const spuCode = codeSuffix.split('.')[0]
        this.spuCode = spuCode
      }
      // 微信扫描智慧屏详情
      const executeScreenScan = (url) => {
        const params = url.split('?').pop()
        const { spuCode } = qs.parse(params) ?? {}
        this.spuCode = spuCode
      }
      // 匹配正则
      const validateRegs = [
        { reg: /(productspu)/g, matchList: ['productspu'], executor: executeTagScan }, // 电子价签扫码
        { reg: /linkApp|spuCode/g, matchList: ['linkApp', 'spuCode'], executor: executeScreenScan } // 智慧屏扫码
      ]
      const scanDetail = validateRegs.find(item => {
        const matchResult = decodeUrl.match(item.reg)
        if (!matchResult) return false
        const matchState = item.matchList.every(res => matchResult.includes(res))
        return matchState
      })
      if (scanDetail) {
        scanDetail.executor(decodeUrl)
        this.isFromWeiXinScan = true
      } else {
        this.$u.toast('没有扫描到相关信息')
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.richImg {
  display: block;
  width: 100%;
}
.topping{
  width: 70rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  position: fixed;
  font-size: 48rpx;
  top: calc(100vh - 330rpx);
  right: 30rpx;
  z-index: 99;
  overflow: hidden;
  box-shadow:0 0 10rpx 4rpx rgba(0,0,0,0.2);
  color: $uni-text-color;
  background: $uni-bg-color;
  border-radius: $uni-border-radius-circle;
}
.hide {
  height: 100vh;
  overflow: hidden;
}
.regionPopup {
  .title {
    width: 100%;
    height: 88rpx;
    padding: 0rpx 32rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    align-content: center;
    font-weight: bold;
    font-size:$uni-font-size-base;
    border-bottom:2rpx solid $uni-border-gray;
    color:$uni-text-color;
    image {
      height: 48rpx;
      width: 48rpx;
    }
  }
}
.shopDetail {
  width: 100%;
}
.indicator-num__text {
  display: flex;
  width: 68rpx;
  height: 32rpx;
  background: #666;
  overflow: hidden;
  font-size: 20rpx;
  text-align: center;
  line-height: 32rpx;
  border-radius:$uni-border-radius-sm;
  color:$uni-text-color-inverse;
  .Active{
    width: 30rpx;
    height: 32rpx;
    background: #222;
  }
  .allLength{
    width: 38rpx;
    height: 100%;
    background: #999;
  }
}
.shopInfo {
  width: 100%;
  padding: 24rpx 32rpx;
  box-sizing: border-box;
  padding-bottom: 0;
  border-radius:$uni-border-radius-default;
}
.shopSpeci {
  padding: 24rpx;
  box-sizing: border-box;
  width: 100%;
  padding-bottom: 32rpx;
  position: relative;
  padding-top: 4rpx;
  background:$uni-bg-color;
  border-radius:$uni-border-radius-default;
}
.activiy {
  display: flex;
  .t-icon{
    width: 64rpx;
    height: 32rpx;
    margin: 5rpx 16rpx 0 0;
  }
  .con-right{
    width:calc(100% - 64rpx);
  }
  .tips {
    word-break: break-all;
    width: 421rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    height: 40rpx;
    white-space: nowrap;
  }
  .time {
    color:$uni-text-color-tips;
    font-size:$uni-font-size-sm;
    margin-top: 8rpx;
  }
}
.timeOut {
  display: flex;
  justify-content: space-between;
  align-content: center;
  align-items: center;
  color:$uni-text-color-grey;
  .time {
    display: flex;
    height: 48rpx;
    justify-content: flex-start;
    padding: 10rpx 24rpx;
    box-sizing: border-box;
    border-top-left-radius: 22rpx;
    border-bottom-left-radius: 22rpx;
    background:$uni-f5bg-color;
    position: absolute;
    right: 0rpx;
    top: 38rpx;
    font-size: 20rpx;
    color: $uni-text-color-grey;
  }
  .redprice{
    color:$uni-text-color-orange;
    font-size:$uni-font-size-sm;
  }
}
.Price {
  font-size: 30rpx;
  color:$uni-text-color-orange;
  display: flex;
  align-items: flex-end;
  align-content: flex-end;
  font-weight: normal;
  .Number {
    font-size: 48rpx;
    font-weight: bold;
    position: relative;
    top: 6rpx;
    color:$uni-text-color-orange;
  }
}
.oldPrice {
  text-decoration:line-through;
  margin-top: 16rpx;
  font-size:$uni-font-size-sm;
  color:$uni-text-color-grey;
}
.activity {
  margin-top: 16rpx;
  display: flex;
  justify-content: space-between;
  .tabs {
    display: flex;
    justify-content: flex-start;
  }
  .moreCop {
    display: flex;
    align-items: center;
    align-content: center;
    justify-content: center;
  }
  .default {
    width: 64rpx;
    height: 32rpx;
    border:2rpx solid #FF5533;
    text-align: center;
    line-height: 32rpx;
    border-radius:$uni-border-radius-sm;
    background:$uni-bg-color;
    color:$uni-text-color-orange;
  }
  .coupons {
    padding: 0rpx 10rpx;
    height: 32rpx;
    background: #FFEBE7;
    line-height: 32rpx;
    text-align: center;
    border: 2rpx solid #FFEBE7;
    margin-right: 16rpx;
    border-radius:$uni-border-radius-sm;
    color:$uni-text-color-orange;
  }
  .defaultStyle {
    float: right;
  }
}
.shopName {
  width: 100%;
  font-weight: bold;
  display: -webkit-box;
  overflow: hidden;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  margin-top: 24rpx;
  color:$uni-text-color;
  font-size:$uni-font-size-base;
}

.describe {
  color:$uni-text-color-grey;
  font-size:$uni-font-size-sm;
  font-weight: normal;
  margin-top: 16rpx;
}

.shopCode {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  align-content: center;
  margin-top: 16rpx;
  color:$uni-text-color-grey;
  font-size:$uni-font-size-sm;
  text {
    color:$uni-text-color!important;
    font-weight: bold;
  }
  .copy {
    width: 80rpx;
    height: 36rpx;
    text-align: center;
    line-height: 36rpx;
    flex-shrink: 0;
    margin-left: 16rpx;
    background: $uni-f5bg-color;
    font-size:$uni-font-size-sm;
    color:$uni-text-color;
  }
}
.tax {
  margin-top: 18rpx;
  display: flex;
  color:$uni-text-color-grey;
  font-size:$uni-font-size-sm;
  .taxPrice {
    color:$uni-text-color;
  }
  .taxRate{
    margin-left: 18rpx;
    color:$uni-text-color;
  }
}
.addressSpeci {
  width: 100%;
  padding: 16rpx 32rpx;
  box-sizing: border-box;
  border-radius:$uni-border-radius-default;
  .addressSpeci_small {
    padding: 24rpx;
    box-sizing: border-box;
    padding-bottom: 32rpx;
    background:$uni-bg-color;
    border-radius:$uni-border-radius-default;
  }
  .speci {
    display: flex;
    justify-content: space-between;
    align-content: center;
    align-items: center;
    color:$uni-text-color-grey;
    font-size:$uni-font-size-base;
    .label {
      display: flex;
      justify-content: flex-start;
      align-content: center;
      align-items: center;
      /deep/.u-icon {
        margin-right: 8rpx;
      }
      .eslineHide {
        width: 400rpx;
        box-sizing: border-box;
        display: -webkit-box;
        overflow: hidden;
        -webkit-box-orient: vertical;
        line-clamp: 1;
        -webkit-line-clamp: 1;
      }
    }
  }
  .speciImage {
    padding-left: 84rpx;
    box-sizing: border-box;
    margin-top: 16rpx;
    display: flex;
    image {
      width: 56rpx;
      height: 56rpx;
      margin-right: 8rpx;
    }
  }
  .tabsServe {
    display: flex;
    width: 100%;
    box-sizing: border-box;
    overflow: hidden;
    -webkit-box-orient: vertical;
    line-clamp: 1;
    -webkit-line-clamp: 1;
    color:$uni-text-color;
    view {
      margin-right: 20rpx;
      display: flex;
      align-items: center;
      align-content: center;
    }
    view:last-child{
      margin: 0;
    }
    image {
      width: 32rpx;
      height: 32rpx;
      margin-right: 8rpx;
    }
    .font_family{
      margin-right: 8rpx;
      font-size:$uni-font-size-lg;
      color: $uni-text-color-tips;
    }
  }
  .labelName {
    flex-shrink: 0;
    width: 84rpx;
  }
  .deliverShop {
    margin-top: 18rpx;
    display: flex;
    align-content: center;
    align-items: center;
    .t-icon {
      width: 56rpx;
      height: 32rpx;
      margin: 0 16rpx 0rpx 84rpx;
    }
  }
}
.detailImage {
  padding: 24rpx 32rpx;
  box-sizing: border-box;
  padding-bottom: 0rpx;
  .line {
    display: block;
    width: 214rpx;
    height: 2rpx;
    background: #AAAAAA;
    position: relative;
    margin: 0 auto;
    margin-bottom: 24rpx;
    view {
      width: 100rpx;
      padding: 0rpx 15rpx;
      position: absolute;
      left: 50%;
      top: -18rpx;
      transform: translateX(-50%);
      background:$uni-f5bg-color;
      font-size:$uni-font-size-sm;
      color:$uni-text-color-grey;
    }
  }
}
.recomShop {
  width: 100%;
  padding: 24rpx 32rpx;
  box-sizing: border-box;
  .title {
    color:$uni-text-color;
    font-size:$uni-font-size-base;
    font-weight: bold;
  }
  .recomShopList {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .small {
      width: 334rpx;
      margin-top: 16rpx;
    }
    .small:nth-child(even) {
      margin-left: 18rpx;
    }
  }
}
</style>
